<?php
namespace App\Services\Infra;

use App\Models\Device;
use App\Models\DeviceRecord;
use App\Models\DeviceType;
use App\Models\UserDevice;
use App\Models\User;
use App\Exceptions\DeviceException;
use DB;
use Exception;

class DeviceManager
{
	/**
     * 增加用户绑定设备记录
     * @param $userId    
     * @param $deviceId 
     */
	public function addUserDevice($userId, $deviceId)
	{
		try{
			$result = UserDevice::where('user_id', $userId)->where('device_id', $deviceId)->first();
			if(is_null($result)){
                $userDevice = new UserDevice();
                $userDevice->user_id = $userId;
	    		$userDevice->device_id = $deviceId;
                $userDevice->save();
			}
		}catch(Exception $e){
			throw new DeviceException('bind');
		}
	}

    /**
     * 是否生成记录
     * @param  string  $deviceCode 
     * @return boolean             
     */
    public function isCreateDeviceRecord($deviceCode, $deviceType)
    {
        $deviceTypeRecord = DeviceType::where('type', $deviceType)->first();
        if(is_null($deviceTypeRecord)){
            $deviceTypeRecord = DeviceType::create([
                'type' => strtoupper($deviceType)
                ]);
        }

        $device = $this->getDeviceByQuery('code', $deviceCode);
        if(is_null($device)){

    		$device = Device::create([
                'code' => $deviceCode,
                'type_id' => $deviceTypeRecord->id,
                ]);
        }
        return $device;
    }

    /**
     * 查询条件获取设备
     * @param  string $column 
     * @param  string $condition 
     * @return
     */
    public function getDeviceByQuery($column, $condition)
    {
    	return Device::where($column, $condition)->first();
    }

    /**
     * 保存设备信息
     * @param  array $data 
     * @return        
     */
    public function addDeviceRecord($data)
    {
        try{
    	   DeviceRecord::create(array_merge($data, ['deivce_id' => $data['device_id']]));
        }catch(Exception $e){
            logger(['DeviceManager@addDeviceRecord' => [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
                'message' => $e->getMessage(),
                ]]);
        }
    }

    /**
     * 根据查询条件获取设备类型
     * @param  string $column    
     * @param  string $condition 
     * @return             
     */
    public function getDeviceTypeByQuery($column, $condition)
    {
        $deviceType = DeviceType::where($column, $condition)->first();
        if(is_null($deviceType)){
            throw new DeviceException('type.notFound');
        }
        return $deviceType;
    }

    /**
     * 根据设备 id 组和设备类型 id 获取设备
     * @param  array  $deviceIds   
     * @param  integer $deviceTypeId 
     * @return                
     */
    public function getDeviceByDeviceIdAndDeviceTypeId($deviceIds, $deviceTypeId)
    {
        $device = Device::whereIn('id', $deviceIds)->where('type_id', $deviceTypeId)->first();
        if(is_null($device)){
            throw new DeviceException('notFound');
        }
        return $device;
    }

    /**
     * 根据设备 id 和用户 id 删除用户绑定记录
     * @param  integer $userId   
     * @param  integer $deviceId 
     * @return
     */
    public function deleteUserDeviceByUserIdAndDeviceId($userId, $deviceId)
    {
        UserDevice::where('user_id', $userId)->where('device_id', $deviceId)->delete();
    }

    /**
     * [getDeviceBuilderByQuery
     * @param   $column    
     * @param   $operation 
     * @param   $data      
     * @return             
     */
    public function getDeviceBuilderByQuery($column, $operation, $data)
    {
        return Device::where($column, $operation, $data);
    }

    /**
     * [getDeviceRecordsBuilderOrderByCreatedAtDesc
     * @param  string $deviceCode 
     * @param  integer $status     
     * @param  integer $typeId     
     * @return              
     */
    public function getDeviceRecordsBuilderOrderByCreatedAtDesc($deviceCode, $status, $typeId)
    {
        $ids = DB::select('select max(id) as id from device_records group by device_id');
        $query = DeviceRecord::whereIn('id', $ids)->latest();

        $deviceBuilder = $this->getDeviceBuilderByQuery('code', 'like', '%'.$deviceCode.'%');
        if(!empty($typeId)) {
            $deviceBuilder->where('type_id', $typeId);
        }
        $devices = $deviceBuilder->get();
        if(!empty($status) && in_array($status, [DeviceRecord::HYDROPENIA, DeviceRecord::OVERHAUL]))
        {
            $query->where('dec_status', $status);
        }
        return $query->whereIn('device_id', $devices->pluck('id'));
    }

    /**
     * 
     * @param  integer $deviceId 
     * @param  integer $status   
     * @return            
     */
    public function getDeviceRecordsByDeviceIdAndStatus($deviceId, $status)
    {
        $query = DeviceRecord::where('device_id', $deviceId);
        if(!empty($status)){
            $query->where('dec_status', $status);
        }
        return $query;
    }

    /**
     * 
     * @param  string $deviceType 
     * @return              
     */
    public function findDeviceTypeBuilderByDeviceType($deviceType)
    {
        return DeviceType::where('type', 'like', '%'.$deviceType.'%');
    }

    /**
     * 
     * @param  array $deviceTypeIds 
     * @return                 
     */
    public function findDeviceBuilderByDeviceTypeIds($deviceTypeIds)
    {
        return Device::whereIn('type_id', $deviceTypeIds);
    }

    /**
     * 获取设备类型builder
     * @return 
     */
    public function getTypeBuilderOrderByCreatedAt()
    {
        return DeviceType::oldest();
    }

    /**
     * 添加设备类型
     * @param array $data 
     */
    public function addType($data)
    {
        DeviceType::create($data);
    }




}